package com.eric.api.ext;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eric.downloader.SimplePageDownloader;
import com.eric.utils.Reader;
import com.eric.utils.TextUtils;

public class ChaXunLaAPI {

	static String cookie;

	File cookieStore = new File("cookie_chaxunla");

	boolean endTag = false;

	public static void main(String[] args) throws MalformedURLException, IOException {
		ChaXunLaAPI c = new ChaXunLaAPI();
		JSONArray pagesReturned = c.downloadKeywordMore("文具", 100);
		// System.out.println((((JSONObject)
		// pagesReturned.get(0)).getJSONArray("data").size()));

		File file = new File("/home/eric/kw_chaxunla_20160920.txt");
		file.createNewFile();
		PrintWriter pw = new PrintWriter(new FileWriter(file));
		//
		// List<String> kwList = new ArrayList<>();
		for (int i = 0; i < pagesReturned.size(); i++) {// 循环取每个页的返回json
			JSONArray curPageKeywordJA = ((JSONObject) pagesReturned.get(i)).getJSONArray("data");
			if (curPageKeywordJA != null) {
				for (int j = 0; j < curPageKeywordJA.size(); j++) {
					String kw = ((JSONObject) curPageKeywordJA.get(j)).getString("a");
					// kwList.add(kw);
					pw.println(kw);
					pw.flush();
				}
			}
		}
		pw.close();
		// System.out.println(kwList.size());
		// System.out.println(kwList);
	}

	private JSONArray downloadKeywordMore(String input, int pages) {// 下载多个页面
		JSONArray ja = new JSONArray();
		for (int i = 1; i <= pages; i++) {
			if (endTag != true) {
				JSONObject json = downloadKeyword1Page(input, i);
				if (json != null)
					ja.add(json);
			}
		}
		return ja;
	}

	private JSONObject downloadKeyword1Page(String input, int pageNum) {// 下载1个页面
		getCookie();
		String query = null;
		try {
			query = "http://api.chaxun.la/api/getWords/?page=" + pageNum + "&k=" + URLEncoder.encode(input, "utf-8")
					+ "&keywordsid=" + cookie;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String response = null;
		try {
			response = new SimplePageDownloader().download(query).text();
		} catch (NullPointerException e) {
			endTag = true;
		}

		JSONObject json = null;
		if (response != null) {
			json = JSONObject.parseObject(TextUtils.removeBom(response));// 移除BOM
		}

		return json;
	}

	private void getCookie() {
		Date date = new Date(cookieStore.lastModified());
		Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);

		if (date.getTime() < today.getTime()) {// cookie已过期，重新下载
			System.out.println("Cookie File Exists But Expired,Downloading! ");
			cookie = downloadCookie();
		} else if (cookieStore.exists()) {// 直接从文件读取cookie
			System.out.println("Cookie File Exists! " + cookieStore.getAbsolutePath());
			cookie = Reader.read2String(cookieStore);
		}

	}

	private String downloadCookie() {
		String password = null;
		try {
			password = URLEncoder.encode(TextUtils.string2Md5("saints"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String s = "http://api.chaxun.la/login/login/?username=eric1981&password=" + password + "&ajax=1";
		String response = new SimplePageDownloader().download(s).text();

		JSONObject json = JSONObject.parseObject(response);
		cookie = json.getString("cookie");

		try {
			PrintWriter pw = new PrintWriter(new FileWriter(cookieStore));
			pw.print(cookie);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return cookie;
	}

}
